<script setup>
import {onBeforeMount, ref} from "vue";
import router from "../../../router";
import {ElMessage} from "element-plus";
import {getResponseData} from "../../../util";
import {listApi} from "../../../api/menu.js";
import {listMyMenusApi, updateMyMenusApi} from "../../../api/role.js";
import MyNav from "../../../components/MyNav.vue";

// 获取当前角色主键和角色名称
let roleId = sessionStorage.getItem('roleId');
let roleName = sessionStorage.getItem('roleName');

/* ==================== 查询角色菜单 ==================== */
// 当前角色拥有的全部菜单列表 + 组件ElTransfer需要的key数组
let myMenus = ref([]);
let valueKeys = ref([]);

async function listMyMenus() {
  let myMenusData = getResponseData(await listMyMenusApi(roleId));
  if (myMenusData) {
    for (let i in myMenusData) {
      // 优化数组结构：该结构是组件ElTransfer需要的
      myMenus.value.push({
        'key': myMenusData[i]['id'],
        'label': myMenusData[i]['name']
      });
      // 组件ElTransfer需要的key数组
      valueKeys.value.push(myMenusData[i]['id']);
    }
  }
}

/* ==================== 查询全部菜单 ==================== */
let allMenus = ref([]);

async function listAllMenus() {
  let allMenusData = getResponseData(await listApi());
  if (allMenusData) {
    for (let i in allMenusData) {
      // 优化数组结构：该结构是组件ElTransfer需要的
      if(allMenusData[i]['pid']){
        allMenus.value.push({
          'key': allMenusData[i]['id'],
          'label': allMenusData[i]['parent']['name'] + ' / ' + allMenusData[i]['name']
        });
      }
    }
  }
}

/* ==================== 确认修改角色 ==================== */
async function updateMyMenus() {
  let res = await updateMyMenusApi({
    'roleId': roleId,
    'menuIds': valueKeys.value
  });
  let data = getResponseData(res);
  if (data) {
    ElMessage.success('菜单列表更新成功！');
    await router.push('/Role')
  }
}

/* ==================== 加载函数 ==================== */
onBeforeMount(() => {
  listMyMenus();
  listAllMenus();
});

</script>

<template>
  <div class="role-menus-body">

    <my-nav :items="[
      {'icon': 'Avatar', 'label': '用户管理', 'url': '/Emp'},
      {'icon': 'User', 'label': '员工列表', 'url': '/Emp'},
      {'icon': 'UserFilled', 'label': '(' + roleName + ') 的菜单列表'},
    ]"/>

    <el-divider/>

    <el-transfer v-if="allMenus"
                 v-model="valueKeys"
                 :data="allMenus"
                 filterable
                 filter-placeholder="输入菜单名称"
                 :titles="['全部可选菜单', '当前已选菜单']"
                 :props="{'key': 'key', 'label': 'label'}"
                 :button-texts="['移除', '添加']"/>

    <el-button class="update-menus-btn"
               type="primary"
               @click="updateMyMenus">确认修改
    </el-button>
  </div>
</template>

<style scoped lang="scss">
.role-menus-body {
  text-align: center; // 内容居中

  .update-menus-btn {
    margin-top: 20px; // 上外边距
    width: 62%; // 宽度
  }
}

/* 修改EL穿梭框高度 */
:deep(.el-transfer-panel), :deep(.el-transfer-panel__body) {
  width: 250px; // 宽度
  height: 500px; // 高度
}
</style>